<?php

global $WSC;

require_once('tcms_vpt_page_wp.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/ci_types/tcms_ci_normal_ci_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_image_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_attachment_dbc.class.php');


class TCMS_VPT_Normal_Page_WP extends TCMS_VPT_Page_WP {
	function __construct(TCMS_VPage_DBC $vpage, TCMS_VPage_Template_DBC $vpt) {
		parent::__construct($vpage, $vpt, 'tcms_vpt_normal_page');
	}


	protected function default_event() {
		$dbc = $this->get_dbc();

		$vpage_cis = TCMS_VPage_CI_DBC::load_cis_for_page($dbc, $this->get_vpage()->get_id());
		foreach($vpage_cis as $vpage_ci) {
			$this->prepare_ci_normal($vpage_ci->get_ci_id());
			break;
		}

		return parent::default_event();
	}


	private function prepare_ci_normal($ci_normal_id) {
		$dbc = $this->get_dbc();

		$ci_normal = new TCMS_CI_Normal_CI_DBC();
		if ($ci_normal->load_by_id($dbc, $ci_normal_id)) {
			$ci_normal_prep = $this->prepare_normal($ci_normal);
			$this->export('content', $ci_normal_prep);

			$ci_id = $ci_normal->get_ci()->get_id();
			$this->export('ci_id', $ci_normal->get_ci()->get_id());

			$this->export_attachments($dbc, $ci_id);
			$this->export_images($dbc, $ci_id);
		}
	}


	private function prepare_normal(TCMS_CI_Normal_CI_DBC $ci_normal) {
		$ret['id'] = $ci_normal->get_ci()->get_id();
		$ret['content'] = $ci_normal->get_content()->get_value();
		$ret['created'] = $ci_normal->get_ci()->get_created();
		$dbc = $this->get_dbc();
		$mod = TCMS_CI_Mod_DBC::load_last_modified_for_ci($dbc, $ci_normal->get_ci()->get_id());
		if ($mod) {
			$ret['last_modified'] = $mod->get_modified_ts();
		} else {
			$ret['last_modified'] = $this->get_vpage()->get_last_modified();
		}

		return $ret;
	}


	public static function get_short_text_description(DB_Connection $dbc, $vpage_id) {
		tangra_if_not_int_throw_e($vpage_id);

		$title_sa = current(TCMS_VPage_System_Attribute_DBC::load_all_by_sa_export_name_vpage($dbc, 'title', $vpage_id));

		if ($title_sa) {
			$ret = $title_sa->get_value();
		} else {
			$ret = '';
		}

		return $ret;
	}
}